package cn.edu.scau.cmi.liangzaoqing.client.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import cn.edu.scau.cmi.liangzaoqing.hibernate.dao.MajorDAO;
import cn.edu.scau.cmi.liangzaoqing.hibernate.domain.Major;

public class HibernateClient4HibernateSession {

	public static void main(String[] args) {
		Major major=new Major();
		major.setName("信息管理");
		major.setId(4L);
		
		newMajor(major);
		listMajors();
	}

		public static void newMajor(Major major) {
//			(1) 可以复用，因此可以抽取出来；
//			(2) SessionFactory应该单例化；
			Session session = new Configuration().configure().buildSessionFactory().openSession();
			
//		s	 session = sf.openSession();
			Transaction transaction = session.beginTransaction();
			
//	 		(1) 直接使用Hibernate的CRUD功能		
			session.save(major);
//			(2) 也可以将Hibernate的CRUD功能封装为DAO后，调用DAO功能。		
//			MajorDAO MajorDAOByHibernate=new MajorDAO();
//			MajorDAOByHibernate.save(Major);
			transaction.commit();
			session.close();
		}

	private static void listMajors() {
//		session加载左右的数据不方便，暂时使用dao
//		SessionFactory sf = new Configuration().configure().buildSessionFactory();
//		Session session = sf.openSession();
//		Major majors = (Major) session.load(Major.class, 1L);
//		
		MajorDAO MajorDAO=new MajorDAO();
		List Majors = MajorDAO.findAll();
		Iterator<?> MajorIterator = Majors.iterator();
		while(MajorIterator.hasNext()){
			Major Major = (Major) MajorIterator.next();
			System.out.println("调用DAO后的专业名是："+Major.getName()+"，调用DAO后的专业ID号是："+Major.getId());
		}
	}
}